package com.xhu.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionFactory {
    // 利用  druid 产生连接数据源
    //产生连接对象
    static DataSource dataSource;
    //只会执行一次  加载配置文件
    static {
        Properties ps=new Properties();
        try {
            System.out.println("================");
            InputStream is =//new FileInputStream("src/main/resources/mysql.properties") ;
             //ClassLoader.getSystemClassLoader().getResourceAsStream("mysql.properties");\
            ConnectionFactory.class.getClassLoader().getResourceAsStream("mysql.properties");
            ps.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(ps);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("====配置文件不存在或者字段内容有误========");
        }
    }

    /**
     * 返回连接对象
     * @return
     */
    public static Connection openConnection()  {
        try {
            return     dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("====用户名或密码错误========");
        }
        return  null;
    }

    /**
     * 释放资源
     * @param connection
     */
    public  static   void  closeConnection(Connection  connection){
         if(connection!=null){
             try {
                 connection.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
    }
}
